package com.icode.lock.threadCommunication.test1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: my_code
 * @Create: 2020-12-10 14:47
 *
 *
 */
public class Data {
    private int num = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment() throws InterruptedException {
        lock.lock();
        try{
            while (num != 0){
                condition.await();
            }
            num ++;
            System.out.println(Thread.currentThread().getName()+"-->" + num);
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (num == 0){
                condition.await();
            }
            num --;
            System.out.println(Thread.currentThread().getName()+"-->" + num);
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }


    }
}
